package com.neo.tiny.middle.socket.websocket;

import com.neo.tiny.middle.socket.websocket.util.SysAdminWebSocketSender;
import com.neo.tiny.token.store.OAuth2AccessToken;
import com.neo.tiny.token.store.TokenStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @Description: 全局系统WebSocket服务
 * @Author: yqz
 * @CreateDate: 2023/2/13 22:38
 */
@Slf4j
@ServerEndpoint("/sys/websocket/{token}")
@Component
public class WebSocketSysServer {

    private static TokenStore tokenStore;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        tokenStore = applicationContext.getBean(TokenStore.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        log.info("创建连接");
        OAuth2AccessToken accessToken = tokenStore.getAccessToken(token);
        Long userId = accessToken.getUserId();
        SysAdminWebSocketSender.addClient(userId, session);
    }

    /**
     * 接收消息
     *
     * @param session
     * @param token
     */
    @OnMessage
    public void onMessage(Session session, String message, @PathParam("token") String token) {

        OAuth2AccessToken accessToken = tokenStore.getAccessToken(token);
        Long userId = accessToken.getUserId();

        log.info("收到:{},的消息：{}", userId, message);

        SysAdminWebSocketSender.sendMsg(userId, message + "！");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("token") String token) {

        OAuth2AccessToken accessToken = tokenStore.getAccessToken(token);
        Long userId = accessToken.getUserId();
        log.info("关闭连接:{}", userId);

        SysAdminWebSocketSender.removeClient(userId);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, @PathParam("token") String token, Throwable error) {
        OAuth2AccessToken accessToken = tokenStore.getAccessToken(token);
        Long userId = accessToken.getUserId();
        SysAdminWebSocketSender.removeClient(userId);
        log.error("发生错误");
        error.printStackTrace();
    }
}
